const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

const winrarPath = 'D:\\WinRAR\\WinRAR.exe';
const password = 'www.sosiba.vip';
const targetDir = 'D:\\360安全浏览器下载\\新建文件夹';
const maxDepth = 10;
const deletePaths = [];
let prevFilePath = '';

// 创建目标目录，如果不存在
if (!fs.existsSync(targetDir)) {
  fs.mkdirSync(targetDir, { recursive: true });
}

// 删除目录及其内容
function deleteDirectory(dirPath) {
  if (fs.existsSync(dirPath)) {
    fs.readdirSync(dirPath).forEach(file => {
      const curPath = path.join(dirPath, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        deleteDirectory(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(dirPath);
  }
}

// 删除最后一个目录及其内容
function deleteLastDirectory(dirPath) {
  const lastDir = path.basename(dirPath);
  const parentDir = path.dirname(dirPath);
  const lastDirPath = path.join(parentDir, lastDir);
  deleteDirectory(lastDirPath);
}

// 复制文件夹内容并删除原文件夹
function copyContentAndDelete(sourceDir, targetDir) {
  return new Promise(resolve => {
    fs.readdirSync(sourceDir).forEach(file => {
      const sourceFilePath = path.join(sourceDir, file);
      const targetFilePath = path.join(targetDir, file);
      if (fs.lstatSync(sourceFilePath).isDirectory()) {
        if (!fs.existsSync(targetFilePath)) {
          fs.mkdirSync(targetFilePath, { recursive: true });
        }
        copyContentAndDelete(sourceFilePath, targetFilePath);
        deletePaths.push(sourceFilePath);
      } else {
        fs.copyFileSync(sourceFilePath, targetFilePath);
      }
    });
    // 在递归结束后删除所有路径
    while (deletePaths.length > 0) {
      const lastPath = deletePaths.pop();
      deleteLastDirectory(lastPath);
    }
    resolve(true);
  });
}

// 解压文件
function unpack(file, depth = 0) {
  return new Promise(resolve => {
    if (depth >= maxDepth) return resolve();
    const ext = path.extname(file);
    const extractedDir = path.join(targetDir, path.basename(file, ext));
    // 创建解压目录，如果不存在
    if (!fs.existsSync(extractedDir)) {
      fs.mkdirSync(extractedDir, { recursive: true });
    }
    // 清空解压目录
    deleteDirectory(extractedDir);
    fs.mkdirSync(extractedDir, { recursive: true });
    // 解压文件
    let command = `${winrarPath} x `;
    command += `-p${password} `;
    command += `"${file}" "${extractedDir}"`;
    exec(command, (error, stdout, stderr) => {
      if (error) {
        console.error(`解压失败，请检查密码是否正确。`, error);
        console.error(`stdout: ${stdout}`);
        console.error(`stderr: ${stderr}`);
        return resolve();
      }
      // 递归处理解压后的文件
      const files = fs.readdirSync(extractedDir);
      files.forEach(async file => {
        const filePath = path.join(extractedDir, file);
        const fileExt = path.extname(filePath);
        if (fileExt === '.zip' || fileExt === '.rar') {
          prevFilePath = filePath;
          await unpack(filePath, depth + 1);
        } else {
          const res = await copyContentAndDelete(extractedDir, targetDir);
          if (res) {
            if (prevFilePath) {
              deleteFileAndDirectory(prevFilePath);
            } else {
              deleteDirectoryRecursively(extractedDir);
              console.log(`目录 ${extractedDir} 已成功删除`);
            }
          }
        }
      });
      resolve();
    });
  });
}

// 递归删除目录及其内容
function deleteDirectoryRecursively(directory) {
  const files = fs.readdirSync(directory, { withFileTypes: true });
  files.forEach(entry => {
    const entryPath = path.join(directory, entry.name);
    if (entry.isDirectory()) {
      // 如果是目录，则递归删除
      deleteDirectoryRecursively(entryPath);
      fs.rmdirSync(entryPath); // 删除空目录
    } else {
      // 如果是文件，则删除文件
      fs.unlinkSync(entryPath);
    }
  });
  // 删除当前目录
  fs.rmdirSync(directory);
}

// 删除文件及其所在目录
function deleteFileAndDirectory(file) {
  const directory = path.dirname(file);
  try {
    fs.unlinkSync(file);
    // 递归删除目录及其内容
    deleteDirectoryRecursively(directory);
    console.log(`文件 ${file} 和目录 ${directory} 已成功删除`);
  } catch (error) {
    console.error(`删除文件失败: ${error.message}：${directory}`);
  }
}

// 主函数
async function main() {
  let inputPath;
  if (process.argv.length < 3) {
    // console.error('请提供要解压的文件或目录路径。');
    // process.exit(1);
    inputPath = 'D:\\360安全浏览器下载\\新建文件夹';
  } else {
    inputPath = process.argv[2];
  }
  if (fs.lstatSync(inputPath).isDirectory()) {
    // 如果是目录，则遍历目录中的所有文件
    const files = fs.readdirSync(inputPath);
    for (const file of files) {
      await unpack(path.join(inputPath, file));
    }
  } else {
    // 如果是单个文件，则直接解压
    await unpack(inputPath);
  }
  // 清理所有记录的路径
  while (deletePaths.length > 0) {
    const lastPath = deletePaths.pop();
    deleteFileAndDirectory(lastPath);
  }
}

main();
